package cn.tianyigps.tianyigpspublic.util;

import cn.tianyigps.tianyigpspublic.param.constant.UrlConstant;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: WEI.YUAN
 * @Descirption:
 * @Date: 2019/4/15_18:46
 */
@Slf4j
public class LocationalUtils {
    private static RestTemplate restTemplate = new RestTemplate();
    /**
     * 根据经纬度获取两点之间的距离(单位：KM)
     *
     * @return
     */
    public static double calcDistance(double lng1, double lat1, double lng2, double lat2) {
        // 计算两定位之间距离
        SpatialContext geo = SpatialContext.GEO;
        return geo.calcDistance(geo.makePoint(lng1, lat1), geo.makePoint(lng2, lat2)) * DistanceUtils.DEG_TO_KM;
    }

    /**
     * 根据经纬度获取具体的地理位置
     * @param lng
     * @param lat
     * @return
     */
    public static String getLocational(Double lng, Double lat) {
        Point point = MapTransformUtils.gcj02tobd09(lng, lat);
        Map<String, Object> param = new HashMap<>();
        param.put("lng", point.getX());
        param.put("lat", point.getY());

        String forObject = restTemplate.getForObject(UrlConstant.BAIDU_GEOCODE, String.class, param);
        ObjectMapper objectMapper = new ObjectMapper();
        String locational = null;
        String addrDetail = null;
        try {
            JsonNode jsonNode = objectMapper.readTree(forObject);
            String result = jsonNode.get("result").toString();
            String address = jsonNode.get("result").get("formatted_address").asText();
            String desc = jsonNode.get("result").get("sematic_description").asText();
            if (StringUtils.isEmpty(address)) {
                return null;
            }
            param.put("addrDetail", result);
            param.put("address", address + desc);

            //具体位置
            locational = param.get("address").toString();
            addrDetail = param.get("addrDetail").toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return locational;


    }
}
